//
//  LineChartView.m
//  CarCare
//
//  Created by ileo on 14-8-6.
//  Copyright (c) 2014年 baozun. All rights reserved.
//

#import "LineChartView.h"

#define LINE_NUMBER 3
#define GAP 0

#define TOP_NUMBER 0.7
#define BOTTOM_NUMBER 1.3

#define DEGREES_TO_RADIANS(angle) ((angle) / 180.0 * M_PI)

@interface LineChartView()

@property (nonatomic, copy) NSArray *yPoints;
@property (nonatomic, copy) NSArray *xPoints;

@property (nonatomic, strong) NSMutableArray *labelsX;
@property (nonatomic, strong) NSMutableArray *labelsY;

@property (nonatomic, assign) CGFloat avgY;

@property (nonatomic, assign) NSInteger x_num;

@property (nonatomic, strong) NSMutableArray *layers;

@end

@implementation LineChartView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        
        self.labelsX = [NSMutableArray arrayWithCapacity:10];
        self.layers = [NSMutableArray arrayWithCapacity:10];
        self.labelsY = [NSMutableArray arrayWithCapacity:LINE_NUMBER];
        
        self.backgroundColor = [UIColor clearColor];
        self.avgY = 0;
        
    }
    return self;
}

-(void)setTitles:(NSArray *)xTitles WithGap:(CGFloat)gap left:(CGFloat)left{
//    _titles = xTitles;
    
    NSInteger max = xTitles.count;
    self.x_num = max;
    
    left += 4;
    
    gap = GAP + gap + 13;
    
    CGFloat width = (self.width - 2 * gap) / max;
    
    for (UIView *view in self.labelsX) {
        [view removeFromSuperview];
    }
    
    for (int i = 0; i < max; i++) {
        UILabel *label;
        if (self.labelsX.count > i) {
            label = self.labelsX[i];
        }else{
            label = [Factory labelWithFrame:CGRectMake(0, 0, 10, 10) font:FONT_DEFAULT_Light(10) text:nil textColor:COLOR_HEXSTRING(@"#868686") onView:nil textAlignment:NSTextAlignmentCenter];
            [self.labelsX addObject:label];
        }
        label.size = CGSizeMake(width, 20);
        label.left = gap + left + width * i;
        label.bottom = self.height - 5;
        label.text = xTitles[i];
        [self addSubview:label];
    }
    
}

-(void)setDatas:(NSArray *)datas WithAvg:(CGFloat)avgNum{

    NSInteger max = datas.count;
    NSMutableArray *tmpYs = [NSMutableArray arrayWithCapacity:max];
    NSMutableArray *tmpXs = [NSMutableArray arrayWithCapacity:max];
    
    CGFloat yMax = 0;
    CGFloat yMin = 0;
    
    CGFloat gap = GAP + 13;
    
    CGFloat width = (self.width - 2 * gap) / max;
    
    for (int i = 0; i < max; i++) {
        [tmpXs addObject:[NSString stringWithFormat:@"%f",gap + width * (i + 0.5)]];
        CGFloat v = [datas[i] floatValue];
        if (v != 0) {
            if (yMin == 0) {
                yMin = v;
            }else if (v != 0) {
                yMin = fminf(yMin, v);
            }
            yMax = fmaxf(yMax, v);
        }
    }
    
    CGFloat height = self.height / LINE_NUMBER;
    
    float lineHeight = self.height - height * (TOP_NUMBER+BOTTOM_NUMBER);
    float ratio = (yMax - yMin) / lineHeight;
    
    for (int i = 0; i < max; i++) {
        CGFloat v = [datas[i] floatValue];
        CGFloat y = 0;
        
        if (v == 0) {
            y = -1;
        }else{
            if (ratio == 0) {
                y = lineHeight / 2 + TOP_NUMBER * height;
            }else{
                y = lineHeight - (v - yMin) / ratio + TOP_NUMBER * height;
            }
        }
        [tmpYs addObject:[NSString stringWithFormat:@"%f",y]];
    }
    
    if (avgNum != 0 && ratio != 0) {
        self.avgY = lineHeight - (avgNum - yMin) / ratio + TOP_NUMBER * height;
    }else if (avgNum == 0) {
        self.avgY = 0;
    }else{
        self.avgY = lineHeight / 2 + TOP_NUMBER * height;
    }
    
    self.xPoints = tmpXs;
    self.yPoints = tmpYs;
    for (UIView *view in self.labelsY) {
        [view removeFromSuperview];
    }
    

    UILabel *label1 , *label2;
    if (self.labelsY.count == 2) {
        label1 = self.labelsY[0];
        label2 = self.labelsY[1];
    }else{
        label1 = [Factory labelWithFrame:CGRectMake(self.width - GAP - 50, 0, 50, 20) font:FONT_DEFAULT_Light(9) text:nil textColor:[COLOR_HEXSTRING(@"#454545") colorWithAlphaComponent:0.4] onView:self textAlignment:NSTextAlignmentRight];
        [self.labelsY addObject:label1];
        
        label2 = [Factory labelWithFrame:CGRectMake(self.width - GAP - 50, 0, 50, 20) font:FONT_DEFAULT_Light(9) text:nil textColor:[COLOR_HEXSTRING(@"#454545") colorWithAlphaComponent:0.4] onView:self textAlignment:NSTextAlignmentRight];
        [self.labelsY addObject:label2];
    }
    
    label1.bottom = height * TOP_NUMBER;
    label2.bottom = height * (1.5 + TOP_NUMBER);
    
    label1.text = [NSString stringWithFormat:@"%0.1f",yMax];
    label2.text = [NSString stringWithFormat:@"%0.1f",yMin];

    [self addSubview:label1];
    [self addSubview:label2];

}

- (void)strokeChart{
    
    for (CALayer *layer in self.layers) {
        [layer removeFromSuperlayer];
    }
    [self.layers removeAllObjects];
    
    NSInteger max = self.yPoints.count;

    CGMutablePathRef linePath = CGPathCreateMutable();
    CGMutablePathRef dashLinePath = CGPathCreateMutable();
//    CGMutablePathRef fillPath = CGPathCreateMutable();
    
    BOOL isDash = NO;
    BOOL isDashStart = NO;

    for (int i = 0; i < max; i++) {
        CGFloat x = [self.xPoints[i] floatValue];
        CGFloat y = [self.yPoints[i] floatValue];
        if (i == 0) {
            if (y != -1) {
//                CGPathMoveToPoint(fillPath, NULL, x, self.height - 30);
//                CGPathAddLineToPoint(fillPath, NULL, x, y);
                CGPathMoveToPoint(linePath, NULL, x, y);
                CGPathMoveToPoint(dashLinePath, NULL, x, y);
                isDashStart = YES;
            }else{
                isDash = YES;
            }
        }else{
            if (!isDash) {
                if (y == -1) {
                    isDash = YES;        
                }else{
                    CGPathAddLineToPoint(linePath, NULL, x, y);
                    CGPathMoveToPoint(dashLinePath, NULL, x, y);
                    isDashStart = YES;
//                    CGPathAddLineToPoint(fillPath, NULL, x, y);
//                    CGPathAddLineToPoint(fillPath, NULL, x, self.height - 30);
//                    CGPathMoveToPoint(fillPath, NULL, x, self.height - 30);
//                    CGPathAddLineToPoint(fillPath, NULL, x, y);
                }
            }else{
                if (y != -1) {
                    isDash = NO;
                    if (isDashStart) {
                        CGPathAddLineToPoint(dashLinePath, NULL, x, y);
                    }else{
                        CGPathMoveToPoint(dashLinePath, NULL, x, y);
                        isDashStart = YES;
                    }
                    CGPathMoveToPoint(linePath, NULL, x, y);
                    
//                    CGPathMoveToPoint(fillPath, NULL, x, self.height - 30);
//                    CGPathAddLineToPoint(fillPath, NULL, x, y);
                }
            }

        }
        
        if (y != -1) {
            CAShapeLayer *point = [self createPointLayerCenter:CGPointMake(x, y)];
            [self.layer addSublayer:point];
            [self.layers addObject:point];
        }
        
    }
    
    CAShapeLayer *line = [self createLineLayer];
    [line setPath:linePath];
    CGPathRelease(linePath);
    
    CAShapeLayer *dashLine = [self createDashLineLayer];
    [dashLine setPath:dashLinePath];
    CGPathRelease(dashLinePath);
    
//    CAShapeLayer *fill = [self createFillLayer];
//    [fill setPath:fillPath];
//    CGPathRelease(fillPath);
    
    [self.layer insertSublayer:line atIndex:0];
    [self.layer insertSublayer:dashLine atIndex:0];
//    [self.layer insertSublayer:fill atIndex:0];
    
    [self.layers addObject:line];
    [self.layers addObject:dashLine];
//    [self.layers addObject:fill];
    
    if (self.avgY != 0) {
        CAShapeLayer *layer = [CAShapeLayer layer];
        layer.fillColor = [UIColor clearColor].CGColor;
        layer.strokeColor = COLOR_HEXSTRING(@"#e5e5e5").CGColor;
        layer.lineWidth = 1.5;
        layer.lineJoin = kCALineJoinRound;
        [layer setLineDashPattern:@[@3,@1]];
        CGMutablePathRef avgPath = CGPathCreateMutable();
        CGPathMoveToPoint(avgPath, NULL, GAP, self.avgY);
        CGPathAddLineToPoint(avgPath, NULL, self.width - GAP, self.avgY);
        [layer setPath:avgPath];
        CGPathRelease(avgPath);
        [self.layer insertSublayer:layer atIndex:0];
        [self.layers addObject:layer];
    }
    
    [self setNeedsDisplay];
    
}

-(CAShapeLayer *)createPointLayerCenter:(CGPoint)point{
    CAShapeLayer *layer = [CAShapeLayer layer];
    layer.fillColor = [UIColor whiteColor].CGColor;
    layer.strokeColor = self.lineColor.CGColor;
    layer.lineWidth = 1.8;
    
    CGMutablePathRef circlePath = CGPathCreateMutable();
    CGPathAddArc(circlePath, NULL, point.x, point.y, 1.9, DEGREES_TO_RADIANS(90), DEGREES_TO_RADIANS(90.1), YES);
    layer.path = circlePath;
    CGPathRelease(circlePath);

    return layer;
}

-(CAShapeLayer *)createLineLayer{
    CAShapeLayer *layer = [CAShapeLayer layer];
    layer.fillColor = [UIColor clearColor].CGColor;
    layer.strokeColor = self.lineColor.CGColor;
    layer.lineWidth = 1.5;
    layer.lineJoin = kCALineJoinRound;
    return layer;
}

-(CAShapeLayer *)createDashLineLayer{
    CAShapeLayer *layer = [self createLineLayer];
    [layer setLineDashPattern:@[@2,@1]];
    return layer;
}

//-(CAShapeLayer *)createFillLayer{
//    CAShapeLayer *layer = [CAShapeLayer layer];
//    layer.fillColor = [COLOR_HEXSTRING(@"#9ec073") colorWithAlphaComponent:0.15].CGColor;
//    layer.strokeColor = [COLOR_HEXSTRING(@"#9ec073") colorWithAlphaComponent:0.01].CGColor;
//    return layer;
//}


// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
    
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextBeginPath(context);
    
    CGContextSetLineCap(context, kCGLineCapRound);
    CGContextSetLineWidth(context, 0.5);

    [COLOR_HEXSTRING(@"#e5e5e5") set];
    CGContextMoveToPoint(context, GAP, self.height - 30);
    CGContextAddLineToPoint(context, self.width - GAP, self.height - 30);
    CGContextStrokePath(context);
    
    [COLOR_HEXSTRING(@"#c5c5c5") set];
    CGContextMoveToPoint(context, GAP, 5);
    CGContextAddLineToPoint(context, self.width - GAP, 5);
    CGContextStrokePath(context);

//    CGFloat lengths[] = {3,1};
//    CGContextSetLineDash(context, 0, lengths, 2);
////    [COLOR_HEXSTRING(@"#e5e5e5") set];
//    CGContextBeginPath(context);
//    
//    CGFloat height = self.height / LINE_NUMBER;
//    CGFloat i = (LINE_NUMBER - TOP_NUMBER - BOTTOM_NUMBER) * 1.5;
//    CGContextMoveToPoint(context, GAP, height * i + 2);
//    CGContextAddLineToPoint(context, self.width - GAP, height * i + 2);
//    CGContextStrokePath(context);

}

@end